/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using Whitemice.ZOGI;
using Whitemice.ZOGI.Backend;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace ObjectWalker
{
  class ObjectWalker : IEntityView
  {    
    MultiResultCallback         callback;
		  
		public static void Main (string[] args)
		{
		  ObjectWalker walker;
		  
		  walker  = new ObjectWalker();

		  if (walker.Establish())
		  {
		    Console.WriteLine("ObjectWalker established");
		    walker.Run();
			} else Console.WriteLine("Unable to establish server connection");  
		}
		
		public ObjectWalker()
		{
		  /* Initialize ZOGI environment */
		  callback = new MultiResultCallback(Callback);
    }
    
    public bool Establish()
    {
      Server.Initialize(); 
		  Server.Connection.Connect("localhost", 80, "adam", "fred123");
	    return Server.Connection.Connected;
	  }
	  
	  public void Run()
	  {
	    TaskListSearchCommand t;
	    
	    Server.Connection.OnException += new ZOGIExceptionHandler(Exception);
		  Server.Connection.OnUserMessage +=  new ZOGIUserMessageHandler(UserMessage);
			Server.Connection.OnReceivedPluginData += new ZOGIPluginDataHandler(PluginData);

      /*
	      FetchCommand z = new FetchCommand(new int[] {    10000,
                                                         10100,
	                                                       10460, 
	                                                    11406084,
	                                                      615850,
	                                                      150650 }, 
	                                        65535, 
	                                        "First");
	      z.Callback = callback;
	      Server.Connection.RunCommand(z);
	      Thread.Sleep(100);

      
			ProjectSearchCommand q;
			
			q = new ProjectSearchCommand("CIS:", null, 65535, "Project");
			q.Callback = callback;
			q.ANDMode();
			Server.Connection.RunCommand(q);

      /*
	    t = new ToDoListSearchCommand(4, "todo");
	    t.Callback = callback;
	    Server.Connection.RunCommand(t);

	    t = new DelegatedListSearchCommand(4, "delegated");
	    t.Callback = callback;
	    Server.Connection.RunCommand(t);
	    
	    t = new ArchivedListSearchCommand(4, "archived");
	    t.Callback = callback;
	    Server.Connection.RunCommand(t);
	    */
      
	    ContactSearchCommand c = new ContactSearchCommand("Search");
	    c.AddANDCriteria("firstName", "Adam", false, false);
	    c.AddORCriteria("phone.number", "616*", true, false);
	    c.Callback = callback;
	    Server.Connection.RunCommand(c);
	    
	    EnterpriseSearchCommand e = new EnterpriseSearchCommand("Search");
	    e.AddANDCriteria("name", "Morri*", true, false);
	    e.AddANDCriteria("address.city", "Grand Rapids", false, false);
	    e.Callback = callback;
	    Server.Connection.RunCommand(e);
	    
	    AppointmentSearchCommand d = new AppointmentSearchCommand(
	      DateTime.Now.Subtract(TimeSpan.FromDays(365)),
	      DateTime.Now.Add(TimeSpan.FromDays(365)),
	      null,
	      new int[] { 10100 },
	      4,
	      "Appointment");
	    d.Callback = callback;
	    Server.Connection.RunCommand(d);

      /*
	    for (int i = 0; i < 0; i++)
	    {
	      FetchCommand z = new FetchCommand(new int[] {10100, 
	                                                           10460, 
	                                                           11406084,
	                                                           3615850,
	                                                           150650}, 
	                                                65535, 
	                                                i);
	      z.Callback = callback;
	      Server.Connection.RunCommand(z);
	      Thread.Sleep(100);
      }
      */
      
      Thread.Sleep(80000);
      
	  } // end Run
   
    public void Callback(object sender, RPCEventArgs args)
		{
      if (args.IsError)
      {
        Console.WriteLine("Exception in callback.");
        Console.WriteLine(args.Exception.Message);
        Console.WriteLine(args.Exception.Source);
        Console.WriteLine(args.Exception.StackTrace);
        return;
      }
		  lock(this)
		  {
        Console.WriteLine("\n************\n");
		    Console.WriteLine("Result#{0} has {1} object(s).", 
                          args.Context, 
                          args.Payload.Count());
		    foreach(Entity r in args.Payload)
		    {
		      Registry.RegisterForNotification(r, this);
		      Console.WriteLine("{0}#{1}", r, r.ObjectId);
          if (r is Whitemice.ZOGI.Contact)
          {
            Console.WriteLine();
            Contact c = (r as Whitemice.ZOGI.Contact);
            Console.WriteLine("First Name: {0}", c.FirstName);
            Console.WriteLine("Last Name: {0}", c.LastName);
            Console.WriteLine("Email#1: {0}", c.EMail1);
            Console.WriteLine("Email#2: {0}", c.EMail2);
            Console.WriteLine("Email#3: {0}", c.EMail3);
            Console.WriteLine("Degree: {0}", c.Degree);
            Console.WriteLine("Description: {0}", c.Description);
            Console.WriteLine("Title: {0}", c.Title);
            
            foreach(Address a in c.Addresses)
            {
              Console.WriteLine("Name1({0}): {1}", a.AddressType, a.Name1);
              Console.WriteLine("Name2({0}): {1}", a.AddressType, a.Name2);
              Console.WriteLine("Name3({0}): {1}", a.AddressType, a.Name3);
              Console.WriteLine("Street({0}): {1}", a.AddressType, a.Street);
              Console.WriteLine("City({0}): {1}", a.AddressType, a.City);
              Console.WriteLine("State({0}): {1}", a.AddressType, a.State);
              Console.WriteLine("Zip({0}): {1}", a.AddressType, a.Zip);
            }
            
            Address m = c.GetAddress("mailing");
            if (m != null)
            {
              Console.WriteLine("Name1({0}): {1}", m.AddressType, m.Name1);
              Console.WriteLine("Name2({0}): {1}", m.AddressType, m.Name2);
              Console.WriteLine("Name3({0}): {1}", m.AddressType, m.Name3);
              Console.WriteLine("Street({0}): {1}", m.AddressType, m.Street);
              Console.WriteLine("City({0}): {1}", m.AddressType, m.City);
              Console.WriteLine("State({0}): {1}", m.AddressType, m.State);
              Console.WriteLine("Zip({0}): {1}", m.AddressType, m.Zip);
            }            
            Console.WriteLine();
          } else if (r is Whitemice.ZOGI.Enterprise)
            {
              Enterprise e = (r as Whitemice.ZOGI.Enterprise);
              Console.WriteLine("Name: {0}", e.Name);   
              Console.WriteLine("URL: {0}", e.URL);
              Console.WriteLine("Bankcode: {0}", e.BankCode);       
              Console.WriteLine();
            } else if (r is Whitemice.ZOGI.Appointment)
              {
                Appointment a = (r as Appointment);
                Console.WriteLine("Title: {0}", a.Title);   
                Console.WriteLine("Location: {0}", a.Location);
                Console.WriteLine("Start: {0}", a.Start);   
                Console.WriteLine("End: {0}", a.End); 
                foreach(Participant p in a.Participants)
                  Console.WriteLine("Participant: {0}", p.ParticipantId); 
                Console.WriteLine();
              } else if (r is Whitemice.ZOGI.Task)
                {
                  Task t = (r as Task);
                  Console.WriteLine("Title: {0}", t.Name);   
                  Console.WriteLine("Keywords: {0}", t.Keywords);
                  Console.WriteLine("Start: {0}", t.Start);   
                  Console.WriteLine("Due: {0}", t.End); 
                  foreach(TaskNotation p in t.Notations)
                  {
                    Console.WriteLine("  Notation: {0}", p.ObjectId); 
                    Console.WriteLine("  Date: {0}", p.Date);
                  }
                } else if (r is Whitemice.ZOGI.Project)
                  {
                    Project o = (r as Project);
                    Console.WriteLine("Title: {0}", o.Name);   
                    Console.WriteLine("Number: {0}", o.Number);
                    Console.WriteLine("Start: {0}", o.Start);   
                    Console.WriteLine("FolderId: {0}", o.FolderId); 
                  }
          Console.WriteLine("\n************\n");
        }
      }
		} // end Callback
		
	  public void UserMessage(string message)
	  {
	  } // end UserMessage

	  public void Exception(Exception exception, 
	                        int faultCode, 
	                        string faultString)
	  {
	    Console.WriteLine("Exception: {0}", exception.Message);
	    Console.WriteLine(exception.StackTrace);
	  } // end Exception
	
	  public void PluginData(Hashtable data)
	  {
	  } // end PluginData
       
    public void Shutdown()
    {
    } // end Shutdown
    
    public void ReceiveEvent(ServerEvent _event)
    {
      Console.WriteLine("Got server event about objectId#{0}", _event.Entity.ObjectId);
    }
  }
}